﻿;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Logistics.HandoverBill", [])
        .controller("HandoverBillCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "$filter", "EventBus", "Upload", "ybConfig", "UserContextService","$http", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, $filter, EventBus, Upload, ybConfig, UserContextService, $http) {
            $scope.activeFlag = [true, false, false, false];
            $scope.datePickerFlag = [false, false, false, false, false, false];
            $scope.subTabFlag = [true, false];
            $scope.materials = [];
            $scope.markInfo = {
                allChecked: false
            };
            $scope.exportBXParam = {
                exportUrl4materialWithNoNcm: ybHttp.RequestUrl("device", "/deliveryReceipt/export4JckBxByBillId")
            };
            // 导出巴西装箱清单（道路）
            $scope.exportBXParamDL = {
                export4DlBxByBillId: ybHttp.RequestUrl("device", "/deliveryReceipt/export4DlBxByBillId")
            };

            $scope.handleBlur = function(e) {
                $scope.condition.outLocations = UserContextService.MultiInput(e.target.value);
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.detailPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.orderMarkInfo = {
                allChecked: false
            };
            $scope.orderPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 200,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };
            $scope.condition = {};
            if ($scope.isKJ)
            {
                $scope.condition.createName = $scope.curUser.name;//add by david
            }


            $scope.orderCondition = {
                status: '1'
            };
            $scope.dataList = [];
            $scope.orderDataList = [];
            $scope.billDetailDataList = [];
            $scope.selectedList = [];
            $scope.detailInfo = {
                sex: 1,
                locked: 0,
                deliveryReceiptVO: {},
                billList: [],
                basicAttachmentList: []
            };
            $scope.abnormalObj = {
                headerInfo: {},
                detailList: []
            };
            $scope.innerOrderList = [];
            $scope.innerOrder = {
                item: null
            };
            $scope.dataSelected = {
                role: {},
                department: {}
            };
            $scope.inTypeList = [];
            $scope.deliveryStatues = [];
            $scope.tabFlag = {};
            $scope.stepList = {
                curStep: 0,
                list: [{
                    name: '选择发货通知单'
                }, {
                    name: '生成发运交接单'
                }]
            };
            $scope.showDatepicker = false;
            $scope.showDatepicker1 = false;
            $scope.packageMethodList = [];
            $scope.packageSpecListAll = [];
            $scope.packageInfo = {
                barcodeList: [],
            };

            $scope.showCommitmentTime = false;
            $scope.warehouseList = [
                {
                    code: null,
                    name: "请选择"
                }
            ];
            $scope.billTypeList = [
                {
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                },
                {
                    code: "XGQD",
                    name: "区域调拨单"
                },
                {
                    code: "XGFC",
                    name: "其它出库单"
                },
                {
                    code: "XSCK",
                    name: "销售赠送出库"
                }
            ];
            $scope.threeDayBillTypeList = [{
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                }
            ];
            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.tableConfig = {
                scrollWidth: 1500,
                fixedWidth: 300,
                tableCol: [
                    {
                        type: "",
                        name: "单号",
                        dataField: "billNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail"
                    },
                    {
                        type: "",
                        name: "打印次数",
                        dataField: "printNum",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户代码",
                        dataField: "dealerOrgId",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "dealerOrgName",
                        width: 150,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "单据类型",
                        dataField: "billTypeDesc",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 80,
                        isShow: !$scope.isWJ,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "采购方式",
                        dataField: "purchaseTypeShow",
                        width: 100,
                        isShow: $scope.isWJ,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发运方式",
                        dataField: "shippingMethod",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "承运商",
                        dataField: "carrierOrgName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "发货日期",
                        dataField: "deliveryDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "物流状态",
                        dataField: "deliveryStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outStatusShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "出库时间",
                        dataField: "outTimeShow",
                        width: 100,
                        isShow: $scope.isDL || $scope.isZHL,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "调度员",
                        dataField: "dispatcherName",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "提货状态",
                        dataField: "takeDeliveryStatusShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "到货时间",
                        dataField: "realArrivalDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "签收时间",
                        dataField: "receiveDateShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "承诺时间（天）",
                        dataField: "commitmentTime",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "是否超期",
                        dataField: "timeOutShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "是否异常",
                        dataField: "isAbnormal",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "是否到货",
                        dataField: "arrivalFlagShow",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "物流更新状态",
                        dataField: "recordFlagShow",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 140,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核状态",
                        dataField: "auditStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核人",
                        dataField: "auditName",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核意见",
                        dataField: "auditMessage",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "审核时间",
                        dataField: "auditDateShow",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "确认发运时间",
                        dataField: "commitTimeShow",
                        width: 160,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "京东物流下发状态",
                        dataField: "syncJdStatusShow",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "京东物流单号",
                        dataField: "wayBillId",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "是否已下达",
                        dataField: "issuedStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        name: "CRM同步状态",
                        dataField: "scSyncCrmStatusShow",
                        width: 120,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "attach",
                        name: "箱单附件",
                        dataField: "packingName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "downloadAttachZL",
                    },
                    {
                        type: "attach",
                        name: "签收附件",
                        dataField: "signAttachName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "downloadAttachCarrier",
                    },
                    {
                        name: "签收附件时间",
                        dataField: "uploadSignBillTime",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "attach4sch",
                        name: "随车附件",
                        dataField: "schAttach",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewAttach4sch",
                    },
                    {
                        name: "结算方式",
                        dataField: "settlementDesc",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        isShow: true,
                        isFixed: true,
                        width: 260,
                    },
                    {
                        name: "承运商ERP同步状态",
                        dataField: "syncWantaiErpFlagDesc",
                        width: 140,
                        isShow: $scope.isWJ,
                        isFixed: false
                    },
                    {
                        name: "承运商ERP同步信息",
                        dataField: "syncWantaiErpRespMsg",
                        width: 200,
                        isShow: $scope.isWJ,
                        isFixed: false
                    },
                    {
                        name: "采购订单审核意见",
                        dataField: "prAuditMessage",
                        width: 200,
                        isShow: $scope.isWJ,
                        isFixed: false
                    },
                    {
                        name: "备注",
                        dataField: "prRemark",
                        width: 120,
                        isShow: $scope.isWJ,
                        isFixed: false
                    },
                ]
            };

            //新增时左侧列表配置项
            $scope.addLeftTableConfig = {
                scrollWidth: 800,
                fixedWidth: 40,
                tableCol: [{
                        type: "",
                        name: "业务单号",
                        dataField: "deliveryNo",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 60,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务信息单号",
                        dataField: "serviceNo",
                        width: 100,
                        isShow: false,
                        isFixed: false,
                        toSort: true,
                        sortType: ''
                    },
                    {
                        type: "",
                        name: "收货地址",
                        dataField: "address",
                        width: 100,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建帐号",
                        dataField: "createName",
                        width: 80,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建时间",
                        dataField: "createDateStr",
                        width: 130,
                        isShow: true,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务人员",
                        dataField: "serviceName",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "服务网点",
                        dataField: "serviceSite",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                    {
                        type: "",
                        name: "创建人",
                        dataField: "createName",
                        width: 80,
                        isShow: false,
                        isFixed: false
                    },
                ]
            };


            $scope.abnormalInNewTbConf = {
                scrollWidth: 950,
                tableCol: [{
                        name: "零件编号",
                        width: 150,
                        dataField: "materialsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "分类",
                        width: 150,
                        dataField: "materialsType",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 120,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "数量",
                        width: 150,
                        dataField: "outQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "已建入库数量",
                        width: 150,
                        dataField: "sendQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "本次入库数量",
                        width: 150,
                        dataField: "amount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "备注",
                        width: 150,
                        dataField: "note",
                        input: true,
                        inputType: "note"
                    }
                ]
            };
            $scope.newTbConf = {
                scrollWidth: 100,
                tableCol: [
                    {
                        name: "零件条码",
                        width: 150,
                        dataField: "barcode",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materiatsNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materiatsDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "数量",
                        width: 150,
                        dataField: "qty",
                        input: false,
                        inputType: ""
                    },
                ]
            };

            var btnPermissionCode = {
                handoverBillAdd: window.ActionCode.handoverBillAdd,
                handoverBillAddAuto: window.ActionCode.handoverBillAddAuto,
                handoverBillEdit: window.ActionCode.handoverBillEdit,
                handoverBillPrint: window.ActionCode.handoverBillPrint,
                handoverBillExport: window.ActionCode.handoverBillExport,
                handoverBillExportJckBatch: window.ActionCode.handoverBillExportJckBatch,
                handoverBillAbnormalIn: window.ActionCode.handoverBillAbnormalIn,
                handoverBillRemove: window.ActionCode.handoverBillRemove,
                handoverBillSend: window.ActionCode.handoverBillSend,
                handoverBillThreeDayPlan: window.ActionCode.handoverBillThreeDayPlan,
                handoverBillReceive: window.ActionCode.handoverBillReceive,
                handoverBillTJSC: window.ActionCode.handoverBillTJSC,
                handoverSaveDetailData: window.ActionCode.handoverSaveDetailData,
                handoverBillEncasementJck: window.ActionCode.handoverBillEncasementJck,
                handoverBillAddPackage: window.ActionCode.handoverBillAddPackage,
                handoverBillBarcodeBox: window.ActionCode.handoverBillBarcodeBox,
                handoverBillAudit: window.ActionCode.handoverBillAudit,
                handoverBillSyncJd: window.ActionCode.handoverBillSyncJd,
                handoverBillExportBXBatch: window.ActionCode.handoverBillExportBXBatch,
                handoverBillUploadPackList: window.ActionCode.handoverBillUploadPackList,
                // 打印装箱清单明细 add by lqx
                handoverBillPrintEncasementD: window.ActionCode.handoverBillPrintEncasementD,
                //导出装箱清单明细 add by lqx
                handoverBillExportDetail: window.ActionCode.handoverBillExportDetail,
                // //未上传签收单
                // handoverBillNotUploadedReceive: window.ActionCode.handoverBillNotUploadedReceive,
                // //未收货
                // handoverBillNotReceive: window.ActionCode.handoverBillNotReceive,
                handoverBillCancelSend: window.ActionCode.handoverBillCancelSend,
                handoverBillWmsSync: window.ActionCode.handoverBillWmsSync,
                handoverBillWmsImport: window.ActionCode.handoverBillWmsImport,
                handoverBillExportBXDLBatch: window.ActionCode.handoverBillExportBXDLBatch,
                handoverBillWTERPSync: window.ActionCode.handoverBillWTERPSync,
                handoverBillWTERPUnsync: window.ActionCode.handoverBillWTERPUnsync,
            };

            $scope.btnPermission = {
                handoverBillAdd: true,
                handoverBillAddAuto: true,
                handoverBillEdit: true,
                handoverBillPrint: true,
                handoverBillExport: true,
                handoverBillExportJckBatch: true,
                handoverBillAbnormalIn: true,
                handoverBillRemove: true,
                handoverBillSend: true,
                handoverBillThreeDayPlan: true,
                handoverBillReceive: true,
                handoverBillTJSC: true,
                handoverSaveDetailData: true,
                handoverBillEncasementJck: true,
                handoverBillAddPackage: true,
                handoverBillBarcodeBox: true,
                handoverBillAudit: true,
                handoverBillSyncJd: true,
                handoverBillExportBXBatch: true,
                handoverBillUploadPackList: true,
                handoverBillPrintEncasementD:true,//打印装箱清单明细 add by lqx
                handoverBillExportDetail:true,//导出装箱清单明细 add by lqx
                // handoverBillNotUploadedReceive:true,//未上传签收单
                // handoverBillNotReceive:true,//未收货
                handoverBillCancelSend: true,
                handoverBillWmsSync: true,
                handoverBillWmsImport: true,
                handoverBillExportBXDLBatch: true, //导出巴西装箱清单（道路）
                handoverBillWTERPSync : true, //同步承运商万泰erp数据
                handoverBillWTERPUnsync : true, //撤销同步承运商万泰erp数据
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }
            
            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    scrollLeft: {
                        left: $scope.tableConfig.fixedWidth + "px"
                    },
                    scrollLeftWidth: {
                        width: $scope.tableConfig.fixedWidth + "px"
                    },
                    billFixedWidth: {
                        left: $scope.addLeftTableConfig.fixedWidth + "px"
                    }
                };
            };
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/export"),
                exportUrl4JckBatch: ybHttp.RequestUrl("device", "/boxupDetail/export4JckBatch"),
                sectionParam: {
                    billIds: []
                },
                allUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/exportAll"),
                allNewUrl: ybHttp.RequestUrl("device", "/deliveryReceipt/exportAllNew"),

                exportUrl: ybHttp.RequestUrl("device", "/boxupDetail/remove"),
                exportUrl4Jck: ybHttp.RequestUrl("device", "/boxupDetail/export4Jck"),
                exportBoxUp: ybHttp.RequestUrl("device", "/deliveryReceipt/exportBoxUp4Batch"),
                exportBoxUpDetailBatch: ybHttp.RequestUrl("device", "/deliveryReceipt/exportBoxUp4BatchOneTable"),
                exportUrl4Detail: ybHttp.RequestUrl("device", "/deliveryReceipt/export4Detail"),
                exportUrl4DLBatch: ybHttp.RequestUrl("device", "/boxupDetail/export4JckBatch"),
            };

            $scope.exportBillDetailParam = {
                url: ybHttp.RequestUrl("device", "/deliveryReceipt/exportBillDetail"),
                param: {
                    billType: "",
                    deliveryBillId: ""
                }
            }

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        $scope.markInfoForAdd = {};
                        $scope.materialsForAdd = [];
                        $scope.headFlagTwo = "";
                        $scope.headFlagThird = "";
                        initData();
                        break;
                    case 1:
                        $scope.headFlagTwo = "";
                        $scope.headFlagThird = "";
                        break;
                    case 2:
                        $scope.headFlagTwo = "detail";
                        break;
                    case 3:
                        $scope.headFlagTwo = "";
                        $scope.headFlagThird = "";
                        break;
                    case 5:
                        $scope.headFlagThird = 'addPackge'
                        $scope.packageInfo.barcode = "";
                        $scope.packageInfo.listForInOutRecord = [];
                        $scope.packageInfo.barcodeList = [];
                        $scope.packageMaterialList.barcodeList = [];
                        addPackage();
                        break;
                    default:
                        $scope.headFlagTwo = "";
                        $scope.headFlagThird = "";
                        break;
                }
            };
            function addPackage(){
                var service = "device";
                var reqUrl = "/boxup/notPackList";
                var param = {
                    deliveryReceiptNo: $scope.detailInfo.deliveryReceiptVO.billNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.packageInfo.notPackageMessageInfo = "该发运交接单号有" + resp.value.length + "条未装箱零件"
                    $scope.packageInfo.notPackageList = resp.value;
                });

                getPackageMethod();
                getPackageSpecListAll();

            }

            function getPackageMethod() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode:"ZXLX"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.packageMethodList = resp.value;
                });
            }
            function getPackageSpecListAll() {
                var service = "device";
                var reqUrl = "/packageSpec/listAll";
                var param = {
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.packageSpecListAll = resp.value;
                });
            }
            $scope.searchBarcode = function () {
                getBarcode();
            };
            $scope.searchBarcodeForBoxup = function () {
                getBarcodeForBoxup();
            };
            function getBarcode() {
				var service = "device";
				var reqUrl = "/warehouseInventory/listForInOutRecordNotPackaged";
				var param = {};
                param.businessOrder = $scope.packageInfo.businessOrder;
                param.type = 0;
				ybHttp.Post(service, reqUrl, param).then(function (resp) {
					if (resp.code !== 0) {
						ybWidget.ShowMessage(resp, MESG_TYPE.Error);
						return;
					}
					$scope.packageInfo.listForInOutRecord = resp.value;
				});
			}
            function getBarcodeForBoxup() {
                var service = "device";
                var reqUrl = "/warehouseInventory/itemByBarcodeForBoxup";
                if(!$scope.packageInfo.barcode){
                    ybWidget.ShowMessage("请选择零件条码", MESG_TYPE.Error);
                    return;
                }
                var param = {
                    receiptNo: $scope.detailInfo.deliveryReceiptVO.billNo,
                    barcode: $scope.packageInfo.barcode
                };
                $scope.packageInfo.barcodeList = [];
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var pushFlag = $scope.packageMaterialList.barcodeList.some(function(item){
                        return(item.barcode == $scope.packageInfo.barcode)
                    })
                    if(!pushFlag){
                        var barcode ={
                            barcode : resp.value[0].barCode,
                            materiatsDes : resp.value[0].materialName,
                            qty : resp.value[0].amount,
                            materiatsNo : resp.value[0].materialNo,
                        }
                        $scope.packageMaterialList.barcodeList.push(barcode);


                    }

                });
            }
            $scope.boxUpAdd = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var param = {
                    depotMode : 1,
                    lenghtNum : $scope.detailInfo.specLong ,
                    withNum : $scope.detailInfo.specWidth ,
                    hightNum : $scope.detailInfo.specHeight ,
                    roughWeight : $scope.detailInfo.weight ,
                    boxCode : $scope.detailInfo.packageName ,
                    deliveryReceiptNo : $scope.detailInfo.deliveryReceiptVO.billNo ,
                    weight : $scope.detailInfo.weight ,
                    roughWeight : $scope.detailInfo.grossWeight ,
                    packCode : $scope.detailInfo.packageMethod,
                };
                var reqUrl = "/boxup/add";
                param.barcodeList = $scope.packageMaterialList.barcodeList;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message, MESG_TYPE.Error);
                        ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                        return;
                    }
                    $scope.headFlagThird = ''; // 关闭新增装箱页
                    $scope.changeTab(2); // 新增装箱成功后 返回到详情页
                    viewDetail({id: $scope.detailInfo.deliveryReceiptVO.id}); // 重新查询详情页数据
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };

            function initData() {
                $scope.sortObj = {};

                $scope.tabFlag = {};
                $scope.detailInfo = {
                    sex: 1,
                    locked: 0,
                    deliveryReceiptVO: {},
                    billList: [],
                    basicAttachmentList: []
                };
                $scope.abnormalObj = {
                    headerInfo: {},
                    detailList: []
                };
                $scope.innerOrder = {
                    item: null
                };
                $scope.selectedList = [];
                $scope.stepList.curStep = 0;
                $scope.dataSelected = {
                    role: {},
                    department: {}
                };
                $scope.billDetailDataList = [];
            }
            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };
            $scope.packageMaterialList = {
                barcodeList:[],
            };

            function getDataList(curPage) {
                $scope.exportParam.sectionParam.billIds = [];
                var service = "device";
                var reqUrl = $scope.isJCHK ? "/deliveryReceipt/list4JckDomestic" : "/deliveryReceipt/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.arrivalDateShow = $filter("YbDate")(item.arrivalDate);
                        item.deliveryDateShow = $filter("YbDate")(item.deliveryDate);
                        item.createDateShow = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.outTimeShow = $filter("YbDate")(item.outTime, 'yyyy-MM-dd HH:mm:ss');
                        item.realArrivalDateShow = $filter("YbDate")(item.realArrivalDate, 'yyyy-MM-dd');
                        item.receiveDateShow = $filter("YbDate")(item.receiveDate, 'yyyy-MM-dd HH:mm:ss');
                        item.billTypeDesc = $filter("orderType")(item.billType);
                        item.outStatusShow = $filter("ProgressStatus")(item.outStatus, 'outDepot');
                        item.timeOutShow = item.isTimeOut < 0 ? "是" : "否";
                        item.isAbnormal = item.isAbnormal === 1 ? "是" : "否";
                        item.arrivalFlagShow = $filter("TrueOrFalseOrNull")(item.arrivalFlag);
                        item.recordFlagShow = $filter("TrueOrFalseOrNull")(item.recordFlag);
                        item.auditDateShow = $filter("YbDate")(item.auditDate, 'yyyy-MM-dd HH:mm:ss');
                        item.commitTimeShow = $filter("YbDate")(item.commitTime, 'yyyy-MM-dd HH:mm:ss');
                        item.auditStatusShow = $filter("ProgressStatus")(Number(item.auditStatus)-1, "auditStatus");
                        item.syncJdStatusShow = item.syncJdStatus === 1 ? "已下发" : "未下发";
                        item.issuedStatusShow = $filter("TrueOrFalseOrNull")(item.issuedStatus);
                        item.scSyncCrmStatusShow = $filter("ProgressStatus")(item.scSyncCrmStatus, "sap");
                        item.deliveryStatusShow = $filter("ProgressStatus")(item.deliveryStatus, 'deliveryStatus');
                        item.uploadSignBillTime = $filter("YbDate")(item.uploadSignBillTime, 'yyyy-MM-dd HH:mm:ss');
                        item.takeDeliveryStatusShow = $filter("ProgressStatus")(item.takeDeliveryStatus, 'takeDeliveryStatus2');
                        item.purchaseTypeShow = `${item.purchaseTypeName||''}${item.purchaseTypeChildName?'-':''}${item.purchaseTypeChildName||''}`;

                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            function changeField(headerInfo) {
                angular.extend($scope.detailInfo.deliveryReceiptVO, headerInfo);
                $scope.detailInfo.deliveryReceiptVO.dealerOrgId = headerInfo.purchaseOrgId;
                $scope.detailInfo.deliveryReceiptVO.dealerOrgName = headerInfo.purchaseOrgName;
                $scope.detailInfo.deliveryReceiptVO.orgName = headerInfo.supplierOrgName;
                $scope.detailInfo.deliveryReceiptVO.createOrgName = headerInfo.createCompanyName;
                $scope.detailInfo.deliveryReceiptVO.shippingMethod = headerInfo.deliveryTypeName;
                $scope.detailInfo.deliveryReceiptVO.settlementId = headerInfo.settleTypeId;
                $scope.detailInfo.deliveryReceiptVO.settlementDesc = headerInfo.settleTypeName;
                $scope.detailInfo.deliveryReceiptVO.receiverName = headerInfo.receiverName;
                $scope.detailInfo.deliveryReceiptVO.receiverTel = headerInfo.receiverPhone;
                $scope.detailInfo.deliveryReceiptVO.receiverFax = headerInfo.receiverFax;
                $scope.detailInfo.deliveryReceiptVO.receiverAddress = headerInfo.address;
                $scope.detailInfo.deliveryReceiptVO.addressCode = headerInfo.addressCode;
                $scope.detailInfo.deliveryReceiptVO.billType = headerInfo.billType;
                if(headerInfo.billType == "XGSC"){
                    $scope.detailInfo.deliveryReceiptVO.remark = $scope.note
                }
                $scope.detailInfo.deliveryReceiptVO.createDate = +new Date();
                $scope.detailInfo.deliveryReceiptVO.deliveryDate = '';
                $scope.detailInfo.deliveryReceiptVO.deliveryTime = $filter("YbDate")(headerInfo.deliveryDate, 'yyyy-MM-dd');
                $scope.detailInfo.deliveryReceiptVO.salesType = '0';
                $scope.detailInfo.deliveryReceiptVO.dispatcherName = headerInfo.dispatcherName;
                $scope.detailInfo.deliveryReceiptVO.carrierOrgName = !!headerInfo.carrier ? headerInfo.carrier : '';
                $scope.detailInfo.deliveryReceiptVO.carrierUserName = !!headerInfo.carrierPerson ? headerInfo.carrierPerson : '';
                if ($scope.isSCH) {
                    $scope.detailInfo.deliveryReceiptVO.deliveryDate = new Date()
                    if (ybConfig.isEnvProd()) {
                        $scope.detailInfo.deliveryReceiptVO.carrierOrgId = '200257571959865344';
                        $scope.detailInfo.deliveryReceiptVO.carrierOrgName = '徐州恒业运输有限公司';
                    } else {
                        $scope.detailInfo.deliveryReceiptVO.carrierOrgId = '647734263617159168';
                        $scope.detailInfo.deliveryReceiptVO.carrierOrgName = '徐州恒业运输有限公司';
                    }
                }
            }

            $scope.orderSelectAll = function () {
                angular.forEach($scope.orderDataList, function (item) {
                    if ($scope.orderMarkInfo.allChecked && !item.isChecked) {
                        item.isChecked = true;
                        $scope.selectedList.push(item);
                    }
                    if (!$scope.orderMarkInfo.allChecked && item.isChecked) {
                        item.isChecked = false;
                        for (var i = 0; i < $scope.selectedList.length; i++) {
                            if (item.deliveryNo == $scope.selectedList[i].deliveryNo) {
                                $scope.selectedList.splice(i, 1);
                                i--;
                            }
                        }
                    }
                })
            };
            $scope.orderSelectSingle = function (item) {
                if (item.isChecked) {
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].deliveryNo === item.deliveryNo) {
                            return;
                        }
                    }
                    $scope.selectedList.push(item);
                    $scope.orderMarkInfo.allChecked = true;
                    angular.forEach($scope.orderDataList, function (item) {
                        if (!item.isChecked) {
                            $scope.orderMarkInfo.allChecked = false;
                        }
                    })
                } else {
                    $scope.orderMarkInfo.allChecked = false;
                    for (var i = 0; i < $scope.selectedList.length; i++) {
                        if ($scope.selectedList[i].deliveryNo == item.deliveryNo) {
                            $scope.selectedList.splice(i, 1);
                            i--;
                        }
                    }
                }
            };
            $scope.delSelected = function (index) {
                angular.forEach($scope.orderDataList, function (item) {
                    if (item.deliveryNo == $scope.selectedList[index].deliveryNo) {
                        item.isChecked = false;
                        $scope.orderMarkInfo.allChecked = false;
                    }
                });
                $scope.selectedList.splice(index, 1);
            };
            $scope.selectDealer = function () {
                var param = {
                    name: "申请单位",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.dealerOrgName = data.companyName;
                    $scope.detailInfo.deliveryReceiptVO.customerId = data.id;
                    $scope.detailInfo.deliveryReceiptVO.dealerOrgId = data.dealerOrgId;
                })
            };

            /* 选择的相邻两项数据中，判断 指定 keyName 信息 是否一致。如：
                1，keyName:'purchaseOrgName'---->判断所选数据是否同一客户
                2，keyName:'address'------------>判断所选数据是否同一收货地址
            */
            function isHasSameValueForKey (keyName, curIdx) {
                return trimALl($scope.selectedList[curIdx][keyName]) === trimALl($scope.selectedList[curIdx + 1][keyName]);
            }

            $scope.nextStep = function () {
                var tempArr = [];
                for (var i = 0, leng = $scope.selectedList.length; i < leng - 1; i++) {
                    if ($scope.isCHY) {
                        // 铲运的只判断客户
                        if (!isHasSameValueForKey('purchaseOrgName', i)) {
                            ybWidget.ShowMessage('只能选择同一个客户发运单');
                            return;
                        }
                    } else if (!$scope.isSWY) {
                        // 施维英的不校验，去后台校验
                        if (!(isHasSameValueForKey('purchaseOrgName', i) && isHasSameValueForKey('address', i))) {
                            ybWidget.ShowMessage('只能选择同一个客户和收货地址的发运单');
                            return;
                        }
                    }

                    if ($scope.orderCondition.billType == 'XGSC' && $scope.selectedList[i].jckClient) {
                        // 三包出库单 且 客户是进出口
                        if (!isHasSameValueForKey('saleNo', i)) {
                            ybWidget.ShowMessage('只能选择同一个三包申请单的发运单');
                            return;
                        }
                    }

                    if (isInArray(tempArr, $scope.selectedList[i].deliveryNo)) {
                        ybWidget.ShowMessage('发运单不能重复，' + $scope.selectedList[i].deliveryNo);
                        return;
                    }

                    if ($scope.isKJ) {
                        var flag =  trimALl($scope.selectedList[i].outArea) === trimALl($scope.selectedList[i + 1].outArea);
                        if (!flag) {
                            ybWidget.ShowMessage('只能选择同一个库区的发运单');
                            return;
                        }
                    }

                    tempArr.push($scope.selectedList[i].deliveryNo);
                }
                $scope.detailInfo.threeDayPlan = $scope.tabFlag.isThreeDayPlan ? 1 : 0;
                $scope.detailInfo.planDate = $scope.orderCondition.planDate;
                $scope.detailInfo.billList = [];
                var note = ""
                angular.forEach($scope.selectedList, function (item) {
                    var threeGuaServiceVO = {
                        prodType: item.prodType,
                        machineNumber: item.machineNumber,
                        crmOrder: item.crmOrder,
                        serviceName: item.serviceName,
                        serviceSite: item.serviceSite,
                    }
                    var obj = {
                        jckClient: item.jckClient,
                        saleBillNo: item.saleNo,
                        deliveryNoteId: item.id,
                        deliveryNoteNo: item.deliveryNo,
                        purchaseBillNo: item.purchaseNo,
                        purchaseContractNo: item.purchaseContractNo,
                        remark: item.note,
                        billType: item.billType,
                        bId: item.bId || '',
                        threeGuaServiceVO: threeGuaServiceVO,
                        status: item.status,

                    };
                    if(item.billType == "XGSC" && item.note){
                        note = note.concat(item.note)
                    }
                    $scope.detailInfo.billList.push(obj);
                });
                $scope.note = note;

                $scope.markInfoForAdd = {};
                $scope.materialsForAdd = [];
                $scope.selectRowForAdd($scope.detailInfo.billList[0], 0);

                getList4MaterialInfoWeight();

                getOutBillItem($scope.selectedList[i].id).then(res => {
                    if (!res) return
                    $scope.stepList.curStep = 1;
                })
            };

            function getOutBillItem(id) {
                return ybHttp.Get('device', '/deliveryReceipt/outBillItem', {
                    id: id,
                    billType: $scope.orderCondition.billType
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    changeField(resp.value || {});
                    return true;
                })
            }

            function isInArray(arr, value) {
                for (var i = 0; i < arr.length; i++) {
                    if (value === arr[i]) {
                        return true;
                    }
                }
                return false;
            }

            function trimALl(str) {
                if (!str) {
                    return str;
                }
                return str.replace(/(^\s*)|(\s*$)/g, "");
            }

            $scope.prevStep = function () {
                $scope.stepList.curStep = 0;
            };

            $scope.sortObj = {};
            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                $scope.sortObj.sortMethod = ybWidget.ToSort(config, index);
                $scope.sortObj.sortClumn = config[index].dataField;
                getBillList(1);
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };
            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    case "downloadAttachZL":
                        downloadAttachZL(item.id);
                        break;
                    case "downloadAttachCarrier":
                        $scope.downloadAttachCarrierFunc(item.id);
                        break;
                    case "viewAttach4sch":
                        viewAttach4sch(item);
                        break;
                    default:
                        break;
                }
            };
            function downloadAttachZL(id) {
                window.location.href = ybHttp.RequestUrl("device", "/deliveryReceipt/downloadPacking") + '?billId=' + id;
            }
           $scope.downloadAttachCarrierFunc=function(id) {
                window.location.href = ybHttp.RequestUrl("device", "/deliveryReceiptLogistics/downloadSignAttach") + '?id=' + id;
            }


            $scope.importAttachZL = function (item) {
                var param = {
                    name: "附件",
                    hideTemplate: true,
                    ignoreFormat: true,
                    importReqService: "device",
                    importReqUrl: "/deliveryReceipt/uploadPacking",
                    importErrorUrl: "",
                    billId: item.id
                };
                ybWidget.ImportFile(param).then(function (data) {
                    getDataList(1);
                });
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };


            $scope.reset = function () {
                const wjPriceExprotFlagTemp = $scope.condition.wjPriceExprotFlag;
                $scope.condition = {
                    wjPriceExprotFlag: wjPriceExprotFlagTemp
                };
            };

            $scope.selectForAll = function () {
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    $scope.dataList[i].isChecked = $scope.markInfo.allChecked;
                }
                getBillIds();
            };

            function checkAll() {
                var selectAll = false;
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!$scope.dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item) {
                if (!item.isChecked) {
                    $scope.markInfo.allChecked = false;
                } else {
                    if (!checkAll()) {
                        $scope.markInfo.allChecked = false;
                    } else {
                        $scope.markInfo.allChecked = true;
                    }
                }
                getBillIds();
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.billIds = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.billIds.push(item.id);
                    }
                });
            }

            $scope.addData = function () {
                $scope.tabFlag = {
                    type: 0,
                    name: tabFlag[0],
                    isThreeDayPlan: false
                };
                $scope.orderCondition.billType = "XGFT";
                getBillList(1);
                $scope.changeTab(1);
            };

            $scope.addThreeDayPlay = function () {
                $scope.tabFlag = {
                    type: 0,
                    name: tabFlag[0],
                    isThreeDayPlan: true
                };
                $scope.orderCondition.billType = "XGFT";
                $scope.orderCondition.planDate = new Date();
                getBillList(1);
                $scope.changeTab(1);
            };

            function getBillList(curPage) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/outBillList";
                if ($scope.tabFlag.isThreeDayPlan) {
                    reqUrl = "/deliveryReceipt/threeDayPlanBillList";
                }
                var param = {};
                param.pageSize = $scope.orderPageInfo.pageSize;
                if (!!curPage) {
                    $scope.orderPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.orderPageInfo.curPage;
                param.filters = {
                    billType: $scope.orderCondition.billType,
                    warehouseCode: $scope.orderCondition.warehouseCode,
                    planDate: $scope.orderCondition.planDate,
                    keyWords: $scope.orderCondition.keWords,
                    sortClumn: $scope.sortObj.sortClumn,
                    sortMethod: $scope.sortObj.sortMethod,
                    queryType: 1
                };
                $scope.orderDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }

                    if (!resp.value) {
                        resp.value = { list: [] }
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                    });
                    $scope.orderPageInfo.totalRows = resp.value.total;
                    $scope.orderPageInfo.totalPages = resp.value.pages;
                    $scope.orderDataList = resp.value.list;
                });
            }

            $scope.searchBill = function (curPage) {
                getBillList(curPage);
            };

            $scope.changeBillType = function () {
                $scope.sortObj = {};

                var dynamicPros = ['serviceName', 'serviceSite', 'createName', 'serviceNo'];
                angular.forEach($scope.addLeftTableConfig.tableCol, function (item) {
                    if (dynamicPros.indexOf(item.dataField) !== -1) {
                        item.isShow = $scope.orderCondition.billType == 'XGSC'
                    }
                })
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.changeWarehouse = function () {
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.changePlanDate = function () {
                console.log("changePlanDate");
                $scope.checkDate($scope.orderCondition, 'planDate');
                $scope.orderDataList = [];
                $scope.selectedList = [];
                $scope.orderMarkInfo.allChecked = false;
                getBillList(1);
            };

            $scope.delData = function (delType, userId) {
                var service = "device";
                var reqUrl = "/profile/remove";
                var param = {};
                param.userIds = [];

                if (delType === "single") {
                    param.userIds.push(userId);
                }
                if (delType === "batch") {
                    for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                        if (!!$scope.dataList[i].isChecked) {
                            param.userIds.push($scope.dataList[i].userId);
                        }
                    }
                    if (param.userIds.length === 0) {
                        ybWidget.ShowMessage('请选择需要删除的行');
                        return;
                    }
                }

                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    ybHttp.Post(service, reqUrl, param.userIds).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    })
                }, function () {

                })
            };

            $scope.selectLogisticsCom = function () {
                var param = {
                    name: "承运物流",
                    type: "carrier"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.carrierOrgId = data.orgId;
                    $scope.detailInfo.deliveryReceiptVO.carrierOrgName = data.companyName;
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = "";
                    $scope.detailInfo.deliveryReceiptVO.commitmentTime = "";
                    $scope.detailInfo.deliveryReceiptVO.basicId = "";
                })
            };

            $scope.selectExpressCode = function () {
                var param = {
                    name: "物流商",
                    type: "logistics"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.expressCode = data.expressCode;
                    $scope.detailInfo.deliveryReceiptVO.expressName = data.expressName;
                })
            };

            $scope.selectLineCom = function () {
                if (!$scope.detailInfo.deliveryReceiptVO.carrierOrgId) {
                    ybWidget.ShowToaster('error', '请选择承运商');
                    return;
                }
                var param = {
                    name: "线路",
                    type: "line",
                    carrierOrgId: $scope.detailInfo.deliveryReceiptVO.carrierOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.deliveryReceiptVO.commitmentTime = data.commitmentTime;
                    $scope.detailInfo.deliveryReceiptVO.basicId = data.id;
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = data.departureCity + "~" + data.destinationCity;
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/getFreight";
                    ybHttp.Get(service, reqUrl, {
                        totalWeight: $scope.totalWeight,
                        logisticsBasicId: $scope.detailInfo.deliveryReceiptVO.basicId
                    }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")(resp.value || 0, 2);
                    });
                })
            };

            $scope.selectBill = function () {
                $scope.selectBillFlag = true;
                var deliveryBillIds = [];
                angular.forEach($scope.detailInfo.billList, function (item) {
                    deliveryBillIds.push(item.deliveryNoteId);
                });
                var param = {
                    billType: $scope.orderCondition.billType,
                    planDate: $scope.detailInfo.planDate,
                    purchaseOrgId: $scope.detailInfo.deliveryReceiptVO.dealerOrgId,
                    deliveryBillIds: deliveryBillIds
                };
                if ($scope.detailInfo.threeDayPlan) param.threeDayPlan = true;

                const needUpdateBillItem = $scope.detailInfo.billList.length == 0
                ybWidget.DeliveryNoteSelector(param).then(function (data) {
                    if ($scope.orderCondition.billType == 'XGSC' && $scope.detailInfo.billList[0].jckClient) {
                        // 三包出库单 且 客户是进出口
                        if (data.saleNo !== $scope.detailInfo.billList[0].saleBillNo) {
                            ybWidget.ShowMessage('只能选择同一个三包申请单的发运单');
                            return;
                        }
                    }

                    var deliveryNoteItem = {
                        deliveryBillId: $scope.detailInfo.deliveryReceiptVO.id,
                        deliveryBillNo: $scope.detailInfo.deliveryReceiptVO.billNo,
                        deliveryNoteId: data.id,
                        deliveryNoteNo: data.deliveryNo,
                        purchaseBillId: '',
                        purchaseBillNo: data.purchaseNo,
                        purchaseContractNo: data.purchaseContractNo,
                        remark: '',
                        saleBillId: '',
                        saleBillNo: data.saleNo,
                        bId: data.bId,
                        status: data.status,
                        billType: data.billType
                    };
                    $scope.detailInfo.billList.push(deliveryNoteItem);

                    getList4MaterialInfoWeight();

                    if (needUpdateBillItem) {
                        getOutBillItem(data.id);
                    }
                })
            };

            function getFreight() {
                var service = "device";
                var reqUrl = "/deliveryReceipt/getFreight";
                ybHttp.Get(service, reqUrl, {
                    totalWeight: $scope.totalWeight,
                    logisticsBasicId: $scope.detailInfo.deliveryReceiptVO.basicId
                }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.deliveryReceiptVO.freight = resp.value;
                });
            }

            function viewDetail(item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/item";
                var param = {};
                param.billId = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var dateFrame = "";
                    $scope.subTabFlag = [true, false];
                    $scope.changeTab(2);
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.deliveryReceiptVO.totalWeight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.totalWeight || 0, 2);
                    $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.freight || 0, 2);
                    if (resp.value.mainVOList.length > 0) {
                        resp.value.mainVOList.forEach(item => {
                            item.takeDeliveryTimeShow = $filter("YbDate")(item.takeDeliveryTime, 'yyyy-MM-dd HH:mm:ss');
                            item.takeDeliveryStatusShow = $filter("ProgressStatus")(item.takeDeliveryStatus, 'takeDeliveryStatus');
                          });
                    }

                    if(resp.value.deliveryReceiptVO.carrierOrgCode === '91320115MA20J0TU4K'){
                        console.log("承运商为万泰");
                    }
                    
                    if (resp.value.logisticsVOList.length > 0) {
                        dateFrame = $filter("YbDate")(resp.value.logisticsVOList[0].createDate);
                        resp.value.logisticsVOList[0].showDate = true;
                    }
                    for (var i = 1, len = resp.value.logisticsVOList.length; i < len; i++) {
                        resp.value.logisticsVOList[i].showDate = true;
                        if ($filter("YbDate")(resp.value.logisticsVOList[i].createDate) === dateFrame) {
                            resp.value.logisticsVOList[i].showDate = false;
                        } else {
                            dateFrame = $filter("YbDate")(resp.value.logisticsVOList[i].createDate);
                        }
                    }

                    if ($scope.isDL || $scope.isZHL) {
                        const mainVOListTemp = resp.value.mainVOList || [];
                        $scope.detailInfo.deliveryReceiptVO.grossWeight = mainVOListTemp.reduce((total,cur) => total + cur.weight || 0, 0).toFixed(2);
                    }

                    $scope.detailInfo = resp.value;

                    EventBus.Publish("setTimeShow", $scope.detailInfo.logisticsVOList);
                });
            }

            $scope.printBill = function (item) {
                var param = {
                    billId: [item.id],
                    printType: "Handover"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.printEncasement = function (item) {
                var param = {
                    billId: [item.id],
                    printType: 'Encasement',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.printEncasementD = function (item) {
                var param = {
                    billId: [item.id],
                    printType: 'EncasementD',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };


            $scope.printEncasementJck = function (item) {             
                var param = {
                    billId: [item.id],
                    printType: 'Encasement4JCK',
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.printEncasementDl = function (item) {
                var param = {
                    billId: [item.id],
                    printType: 'Encasement4JCK',
                    cusInterface: '/deliveryReceipt/item4DlAndZl'
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.delivery = function (item) {
                $scope.detailInfo.deliveryReceiptVO.isAbnormal = !item.isAbnormal ? 0 : (item.isAbnormal === '否' ? 0 : 1);
                $scope.detailInfo.deliveryReceiptVO.remark = item.remark;
                $scope.detailInfo.deliveryReceiptVO.id = item.id;
                if (item.attachName) {
                    var fileObj = {};
                    fileObj.name = item.attachName;
                    fileObj.value = item.attachName;
                    $scope.detailInfo.basicAttachmentList.push(fileObj);
                }
                $scope.changeTab(4);
            };
            $scope.deliveryConfirm = function () {
                var service = "device";
                var reqUrl = "/deliveryReceipt/confirmReceipt";
                if ($scope.detailInfo.deliveryReceiptVO.isAbnormal) {
                    if (!$scope.detailInfo.deliveryReceiptVO.remark) {
                        ybWidget.ShowMessage("请填写备注", MESG_TYPE.Error);
                        return;
                    }
                    reqUrl = "/deliveryReceipt/refusedReceipt";
                }
                var param = {};
                param.id = $scope.detailInfo.deliveryReceiptVO.id;
                param.receiveMessage = $scope.detailInfo.deliveryReceiptVO.remark;
                param.isAbnormal = $scope.detailInfo.deliveryReceiptVO.isAbnormal;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    getDataList();
                    $scope.changeTab(0);
                    ybWidget.ShowToaster('success', '操作成功');
                });
            };
           //在承运商及工厂端增加筛选按钮名为：未上传签收单，此按钮筛选代理商签收发运单时间到当前时间超过8日，承运商未上传签收单的单据
            //在代理商及工厂端增加筛选按钮名为：未收货，此按钮筛选承运商上传签收单时间到当前时间超过5日，代理商未收货的单据
            //（都为自然日，不区分节假日）
            $scope.notUploadedReceive = function () {
                if($scope.condition.warnUnuploadFlagParam){
                    $scope.condition.warnUnuploadFlag=1;
                }else{
                    $scope.condition.warnUnuploadFlag=0;
                }
            };
            $scope.notReceive = function () {
                if($scope.condition.warnUnsignFlagParam){
                    $scope.condition.warnUnsignFlag=1;
                }else{
                    $scope.condition.warnUnsignFlag=0;
                }
            };
            $scope.editBox = function (item) {
                var param = item;
                ybWidget.BoxEditMsg(param).then(function (value) {
                    var service = "device";
                    var reqUrl = "/boxup/update";
                    ybHttp.Post(service, reqUrl, value).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        item = value;
                    });
                });
            }
            $scope.editData = function (item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/item";
                var param = {};
                param.billId = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(1);
                    $scope.stepList.curStep = 1;
                    if (resp.value.planDate) {
                        resp.value.planDate = $filter("YbDate")(resp.value.planDate);
                    }
                    $scope.detailInfo = resp.value;
                    $scope.totalWeight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.totalWeight || 0, 2);
                    $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.freight || 0, 2);
                    $scope.orderCondition.billType = resp.value.deliveryReceiptVO.billType;
                    if (resp.value.deliveryReceiptVO.deliveryTime) {
                        $scope.detailInfo.deliveryReceiptVO.deliveryTime = new Date(resp.value.deliveryReceiptVO.deliveryTime);
                    }
                    if (resp.value.deliveryReceiptVO.deliveryDate) {
                        $scope.detailInfo.deliveryReceiptVO.deliveryDate = new Date(resp.value.deliveryReceiptVO.deliveryDate);
                    }
                    if ($scope.detailInfo.deliveryReceiptVO.basicId) {
                        getLine($scope.detailInfo.deliveryReceiptVO.basicId)
                    }

                    // isDealerJck 判断有bug。resp.value.deliveryReceiptVO.dealerOrgId 是进出口作为主机厂客户时的 客户orId，并非进出口的平台orgId:window.JCHK_ORG_IDs
                    $scope.isDealerJck = window.JCHK_ORG_IDs.includes(resp.value.deliveryReceiptVO.dealerOrgId); // 客户是否是进出口
                });
            };

            function getLine(basicId) {
                var service = 'device';
                var reqUrl = '/logisticsBasic/item';
                var param = {
                    id: basicId
                };

                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailInfo.deliveryReceiptVO.selectedLine = resp.value.departureCity + "~" + resp.value.destinationCity;
                });

            }
            $scope.clickValue = false;
            $scope.saveDataflag = 0;
            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.clickValue) {
                    return;
                }
                if ($scope.saveDataflag == 1) {
                    return;
                };
                setTimeout(function () {
                    $scope.saveDataflag = 0;
                }, 2000);
                $scope.saveDataflag++;
                $scope.clickValue = true;
                var service = "device";
                var reqUrl = "/deliveryReceipt/submit";
                $scope.detailInfo.deliveryReceiptVO.totalWeight = $scope.totalWeight
                var param = $scope.detailInfo;
                param.billId = $scope.detailInfo.id;
                if ($scope.tabFlag.type === 1) {
                    reqUrl = "/deliveryReceipt/update";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        $scope.clickValue = false;
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    $scope.selectedList = [];
                    getDataList();
                    $scope.markInfo.allChecked = false;
                    $scope.orderMarkInfo.allChecked = false;
                    $scope.clickValue = false;
                });
            };

            function getDeliveryStatus() {
                var service = "device";
                var reqUrl = "/dataDictionary/searchList";
                var param = {
                    parentCode: "WLZT"
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.deliveryStatues = resp.value;
                })
            }

            function getMoreDetailist(curPage) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/moreBillDetail";
                var param = {};
                param.pageSize = $scope.detailPageInfo.pageSize;
                if (!!curPage) {
                    $scope.detailPageInfo.curPage = curPage;
                }
                param.pageNum = $scope.detailPageInfo.curPage;
                param.filters = {
                    billType: $scope.detailInfo.deliveryReceiptVO.billType,
                    deliveryBillId: $scope.detailInfo.deliveryReceiptVO.id
                };
                $scope.billDetailDataList = [];
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.detailPageInfo.totalRows = resp.value.total;
                    $scope.detailPageInfo.totalPages = resp.value.pages;

                    angular.forEach(resp.value.list, function (item) {
                        item.arrivalTime = item.arrivalTime ? new Date(item.arrivalTime) : '';
                    });
                    $scope.billDetailDataList = resp.value.list;
                });
            }

            $scope.saveDetailData = function (item) {
                var service = "device";
                var reqUrl = "/deliveryReceipt/billDetail/edit";
                var param = {
                    billType: 'XGSC',
                    outDetailId: item.outDetailId,
                    backFactory: item.backFactory,
                    remark: item.remark,
                    arrivalTime: item.arrivalTime ? item.arrivalTime.getTime() : undefined

                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                })
            };

            $scope.searchDetail = function (curPage) {
                getMoreDetailist(curPage);
            };
            $scope.initDetail = function (curPage) {
                if (!!$scope.billDetailDataList && $scope.billDetailDataList.length > 0) {
                    return;
                }
                $scope.exportBillDetailParam.param.billType = $scope.detailInfo.deliveryReceiptVO.billType;
                $scope.exportBillDetailParam.param.deliveryBillId = $scope.detailInfo.deliveryReceiptVO.id;
                getMoreDetailist(curPage);
            };

            $scope.makeAbnormal = function (receiptId, receiptNo, orgId) {
                getReceiptDetail(receiptId).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.abnormalObj.headerInfo = {
                        receiptId: receiptId,
                        receiptNo: receiptNo,
                        supplierOrgId: orgId
                    };
                    angular.forEach(data, function (item) {
                        if (item.outQty > item.sendQty) {
                            item.amount = item.outQty - item.sendQty;
                            item.canQty = item.amount;
                            $scope.abnormalObj.detailList.push(item);
                        }
                    });
                    $scope.changeTab(3);
                    if ($scope.inTypeList.length === 0) {
                        getTypeList();
                    }
                });
            };

            function getTypeList() {
                var service = "device";
                var reqUrl = "/billTypeConfig/list";
                var param = {
                    filters: {
                        inOut: 0
                    },
                    pageNum: 0,
                    pageSize: 0
                };
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.inTypeList = resp.value.list;
                })
            }

            function getReceiptDetail(receiptId) {
                var param = {
                    receiptId: receiptId
                };
                return ybHttp.Get('device', '/deliveryReceipt/materialsList', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value;
                });
            }

            $scope.saveAbnormalInData = function (isValid) {
                if (angular.isDefined(isValid) && !isValid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.abnormalObj.detailList.length === 0) {
                    ybWidget.ShowToaster('error', '零件不可为空');
                    return;
                }
                var listValid = checkListValid();
                if (!listValid) {
                    return;
                }
                var service = "device";
                var reqUrl = "/receiptIn/add";
                var param = angular.copy($scope.abnormalObj);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    if ($scope.tabFlag.type === 0) {
                        getDataList(1);
                    } else {
                        getDataList();
                    }
                    $scope.changeTab(0);
                });
            };

            function checkListValid() {
                var isValid = true;
                var errMsgStr = "";
                for (var i = 0, len = $scope.abnormalObj.detailList.length; i < len; i++) {
                    if (!$scope.abnormalObj.detailList[i].amount || parseFloat($scope.abnormalObj.detailList[i].amount) <= 0) {
                        isValid = false;
                        $scope.abnormalObj.detailList[i].qtyErr = true;
                        $scope.abnormalObj.detailList[i].qtyErrMsg = "入库数量不能为空和0";
                        errMsgStr = "零件" + $scope.abnormalObj.detailList[i].materialsNo + "：入库数量不能为空和0";
                        break;
                    }
                    if ($scope.abnormalObj.detailList[i].amount > $scope.abnormalObj.detailList[i].canQty) {
                        isValid = false;
                        $scope.abnormalObj.detailList[i].qtyErr = true;
                        $scope.abnormalObj.detailList[i].qtyErrMsg = "入库数量不能大于可入库数量";
                        errMsgStr = "零件" + $scope.abnormalObj.detailList[i].materialsNo + "：入库数量不能大于可入库数量";
                        break;
                    }
                }
                if (!isValid) {
                    ybWidget.ShowMessage(errMsgStr, MESG_TYPE.Error);
                }
                return isValid;
            }

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseUsingSelector().then(function (data) {
                    if (!!$scope.abnormalObj.headerInfo.warehouseCode && (data.warehouseCode !== $scope.abnormalObj.headerInfo.warehouseCode)) {
                        $scope.abnormalObj.headerInfo.inArea = "";
                        $scope.abnormalObj.headerInfo.sapInArea = "";
                    }
                    $scope.abnormalObj.headerInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.abnormalObj.headerInfo.warehouseCode = "";
                $scope.abnormalObj.headerInfo.inArea = "";
                $scope.abnormalObj.headerInfo.sapInArea = "";
            };

            $scope.selectArea = function () {
                if (!$scope.abnormalObj.headerInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择领入仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.abnormalObj.headerInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.abnormalObj.headerInfo.inArea = data.areaCode;
                    $scope.abnormalObj.headerInfo.sapInArea = data.sapCode;
                })
            };

            $scope.clearArea = function () {
                $scope.abnormalObj.headerInfo.inArea = "";
                $scope.abnormalObj.headerInfo.sapInArea = "";
            };

            $scope.getInnerOrderList = function (billTypeId) {
                $scope.innerOrderList = [];
                $scope.innerOrder = {
                    item: null
                };
                var service = "device";
                var reqUrl = "/billTypeConfig/item";
                var param = {};
                param.id = billTypeId;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.innerOrderList = resp.value.detailList;
                });
            };

            $scope.delApply = function (item) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/remove";
                    var obj = {};
                    obj.id = item.id;
                    ybHttp.Post(service, reqUrl, obj).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            function listWarehouses() {
                var service = "device";
                var reqUrl = "/warehouse/listWarehouses";
                var param = {};
                param.pageSize = 100;
                param.pageNum = 1;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var flag = false;
                    angular.forEach(resp.value.list, function (item) {
                        var warehouse = {};
                        warehouse.code = item.warehouseCode;
                        warehouse.name = item.warehouseCode;
                        $scope.warehouseList.push(warehouse);
                        if ("WJBJ" === item.warehouseCode) {
                            flag = true;
                        }
                    });

                    if (flag) {
                        $scope.orderCondition.warehouseCode = "WJBJ";
                    }
                });
            }

            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.abnormalObj.detailList.splice(index, 1);
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.abnormalObj.detailList.length; i < len; i++) {
                    if (!!$scope.abnormalObj.detailList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.abnormalObj.detailList.length - 1; i >= 0; i--) {
                        if (!!$scope.abnormalObj.detailList[i].isChecked) {
                            $scope.abnormalObj.detailList.splice(i, 1);
                        }
                    }
                    if ($scope.abnormalObj.detailList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.sendConfirm = function (billNo) {
                ybWidget.ShowMessage("确定要确认发货吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/shipConfirm";
                    var param = {
                        billNo: billNo
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.cancelSend = function (billNo) {
                ybWidget.ShowMessage("确定取消发货吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/reShipConfirm";
                    var param = {
                        billNo: billNo
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.outPut = function () {
                if (!$scope.condition.billType) {
                    ybWidget.ShowMessage('请选择单据类型');
                    return false;
                }
                return true;
            };

            $scope.uploadDoc = function (file, index) {
                if (!file) {
                    return;
                }
                if (!/\.(xlsx|xls|doc|docx|pdf|jpeg|png|rar|zip|XLSX|XLS|DOC|DOCX|PDF|JPEG|PNG)$/.test(file.name)) {
                    ybWidget.ShowMessage("请选择 .xlsx .xls .doc .docx .pdf .jpeg .png .rar .zip  格式的文件", MESG_TYPE.Error);
                    return;
                }
                Upload.upload({
                    url: ybConfig.getConfig().baseUrl.Site + "zuul/" + ybConfig.getConfig().serviceName.device + '/deliveryReceipt/uploadAttach',
                    data: {
                        file: file,
                        fileName: file.name,
                        "x-billId": $scope.detailInfo.deliveryReceiptVO.id
                    }
                }).then(function (resp) {
                    var fileObj = {};
                    fileObj.name = resp.config.data.fileName;
                    fileObj.value = resp.data.value;
                    $scope.detailInfo.basicAttachmentList.push(fileObj);
                }, function (resp) {
                    ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                });
            };

            //删除附件
            $scope.delEnclosure = function (index) {
                $scope.detailInfo.basicAttachmentList.splice(index, 1);
            };

            $scope.downloadAttach = function (id) {
                window.location.href = ybHttp.RequestUrl("device", "/deliveryReceipt/downloadAttach") + '?id=' + id;
            };

            $scope.syncData = function () {
                var service = "device";
                var reqUrl = "/deliveryReceipt/getExpressInfo";
                var param = {
                    deliveryReceiptNo: $scope.detailInfo.deliveryReceiptVO.billNo
                };
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var reqServerUrl = "/deliveryReceipt/item";
                    var param1 = {
                        billId: $scope.detailInfo.deliveryReceiptVO.id
                    };
                    ybHttp.Get(service, reqServerUrl, param1).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        var dateFrame = "";
                        $scope.detailInfo = resp.value;
                        console.log("syncData resp.value.logisticsVOList:",resp.value.logisticsVOList);
                        if (resp.value.logisticsVOList.length > 0) {
                            dateFrame = $filter("YbDate")(resp.value.logisticsVOList[0].createDate);
                            resp.value.logisticsVOList[0].showDate = true;
                        }
                        for (var i = 1, len = resp.value.logisticsVOList.length; i < len; i++) {
                            resp.value.logisticsVOList[i].showDate = true;
                            if ($filter("YbDate")(resp.value.logisticsVOList[i].createDate) === dateFrame) {
                                resp.value.logisticsVOList[i].showDate = false;
                            } else {
                                dateFrame = $filter("YbDate")(resp.value.logisticsVOList[i].createDate);
                            }
                        }
                        $scope.detailInfo = resp.value;
                        EventBus.Publish("setTimeShow", $scope.detailInfo.logisticsVOList);
                        ybWidget.ShowToaster('success', '同步成功');
                    })
                });
            };

            $scope.batchPrint = function () {
                var billIds = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIds.push($scope.dataList[i].id);
                    }
                }
                if (billIds.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "Handover",
                    cusInterface: '/deliveryReceipt/batchPrintWithUpdate',
                    cusParam: { billIds },
                    isBatchPrint: true
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.barcodePrint = async function (item) {
                var param = {
                    billId: item.id,
                };
                var lodop = UserContextService.GetLodop();
                if (!lodop) {
                    return;
                }

                if (!await UserContextService.InitPrinter(lodop, true, 6)) {
                    return;
                }

                var service = "device";
                var reqUrl = "/deliveryReceipt/getPrintBoxupInfo";
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp.message, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.boxInfos,function(item){
                        item.billNo = resp.value.billNo
                    })
                    UserContextService.CreatPrintTplByPrintType(lodop,resp.value.boxInfos, 6).then(function () {
                        lodop.PREVIEW();
                    });
                });
            };

            $scope.batchPrintJckBoxup = function () {
                var billIdList = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billIdList.push($scope.dataList[i].id);
                    }
                }
                if (billIdList.length === 0) {
                    ybWidget.ShowMessage('请选择需要打印的行');
                    return;
                }
                var param = {
                    printType: "Encasement4JCK",
                    cusInterface: '/deliveryReceipt/batch4Print',
                    cusParam: { billIdList }
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.batchSendConfirm = function () {
                var billNos = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        billNos.push({
                            "billNo": $scope.dataList[i].billNo
                        });
                    }
                }
                if (billNos.length === 0) {
                    ybWidget.ShowMessage('请选择需要确认发货的行');
                    return;
                }
                ybWidget.ShowMessage("确定要确认发货吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/batchShipConfirm";
                    ybHttp.Post(service, reqUrl, billNos).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                            return;
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.markInfoForAdd = {};
            $scope.materialsForAdd = [];

            function getList4MaterialInfoWeight() {
                var billTypeRes = $scope.tabFlag.type == 1 ? $scope.detailInfo.deliveryReceiptVO.billType : $scope.orderCondition.billType;
                var params = {
                    billNos: $scope.detailInfo.billList.map(function (item) {
                        return item.deliveryNoteNo;
                    }),
                    billType: billTypeRes
                };
                ybHttp.Get('device', '/deliveryReceipt/list4MaterialInfo', params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    var materialInfos = typeof resp.value === 'string' ? [] : resp.value;
                    $scope.totalWeight = materialInfos.reduce(function (total, cur) {
                        if (billTypeRes == 'XGQD') {
                            return total + (cur.weight || 0) * cur.amount
                        }
                        return total + (cur.weight || 0) * cur.qty
                    }, 0)
                    $scope.totalWeight = $filter("decimalPlaces")($scope.totalWeight || 0, 2);
                    if (!!$scope.selectBillFlag) {
                        getFreight()
                        $scope.selectBillFlag = false;
                    }
                    if (!!$scope.delBillFlag) {
                        getFreight();
                        $scope.delBillFlag = false;
                    }
                })
            };

            $scope.selectRowForAdd = function (item, index) {
                if ($scope.markInfoForAdd.cueRow == index) return;
                $scope.markInfoForAdd.cueRow = index;

                var billTypeRes = $scope.tabFlag.type == 1 ? $scope.detailInfo.deliveryReceiptVO.billType : $scope.orderCondition.billType;
                var params = {
                    billNos: [item.deliveryNoteNo],
                    billType: billTypeRes
                };
                ybHttp.Get('device', '/deliveryReceipt/list4MaterialInfo', params).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.materialsForAdd = typeof resp.value === 'string' ? [] : resp.value;
                    angular.forEach($scope.materialsForAdd, function (item) {
                        switch (billTypeRes) {
                            case 'XGFT': // 发货通知单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDes;
                                item.qtyC = item.qty;
                                break;
                            case 'XGSC': // 三包出库单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDesc;
                                item.qtyC = item.qty;
                                break;
                            case 'XGQD': // 区域调拨单
                                item.materialNoC = item.materialNo;
                                item.materialDesC = item.materialName;
                                item.qtyC = item.amount;
                                break;
                            case 'XGFC': // 其它出库单
                                item.materialNoC = item.materialsNo;
                                item.materialDesC = item.materialsDes;
                                item.qtyC = item.qty;
                                break;
                            case 'XSCK': // 销售赠送出库
                                item.materialNoC = item.materialNo;
                                item.materialDesC = item.materialName;
                                item.qtyC = item.amount;
                                break;
                            case 'XGZK': // 赠送出库
                                item.materialNoC = item.materialsNo; 
                                item.materialDesC = item.materialsDesc;
                                item.qtyC = item.qty;
                                break;    
                        }
                    })
                })
            };
            $scope.delBill = function (index, e) {
                e.stopPropagation();
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.detailInfo.billList.splice(index, 1);
                    $scope.delBillFlag = true;
                    getList4MaterialInfoWeight();

                    if (index == $scope.markInfoForAdd.cueRow) {
                        $scope.markInfoForAdd = {};
                        $scope.materialsForAdd = [];
                    } else if (index < $scope.markInfoForAdd.cueRow) {
                        $scope.markInfoForAdd.cueRow -= 1;
                    }
                });
            };

            $scope.auditBill = function (item) {
                $scope.auditMessage = {};
                var service = "device";
                var reqUrl = "/deliveryReceipt/item";
                var param = {};
                param.billId = item.id;
                $scope.auditId = item.id;
                ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.changeTab(6);
                    $scope.detailInfo = resp.value;
                    $scope.detailInfo.deliveryReceiptVO.totalWeight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.totalWeight || 0, 2);
                    $scope.detailInfo.deliveryReceiptVO.freight = $filter("decimalPlaces")($scope.detailInfo.deliveryReceiptVO.freight || 0, 2);
                    $scope.detailInfo = resp.value;

                });
            };

            $scope.auditMessage = {};
            $scope.handleAudit = function(type, ids, msg) {
                var service = "device";
                var reqUrl = "";
                var param = {
                    ids: ids || [$scope.auditId]
                };

                var msgStr = msg || $scope.auditMessage.value;
                if (type == 1) {
                    // 通过
                    reqUrl = "/deliveryReceipt/auditPass"
                } else if (type == 2) {
                    // 拒绝
                    if (!msgStr) {
                        ybWidget.ShowMessage("请填写审核意见", MESG_TYPE.Error);
                        return
                    }
                    reqUrl = "/deliveryReceipt/auditReject"
                }
                param.auditRemark = msgStr;

                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList();
                    $scope.changeTab(0);
                });
            };

            $scope.auditData = function () {
                $scope.auditMessage = {};
                var ids = [];
                for (var i = 0, len = $scope.dataList.length; i < len; i++) {
                    if (!!$scope.dataList[i].isChecked) {
                        ids.push($scope.dataList[i].id);
                    }
                }
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请正确选择需要审核的行');
                    return;
                }
                ybWidget.AuditMsg({
                    passCb: function(val) {
                        return $scope.handleAudit (1, ids, val)
                    },
                    refuseCb: function(val) {
                        return $scope.handleAudit (2, ids, val)
                    }
                })
            };

            $scope.syncJd = function (item) {
                ybWidget.ShowMessage("确定要下发吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/deliveryReceipt/syncDelivery4JD";
                    var obj = {};
                    obj.billId = item.id;
                    ybHttp.Get(service, reqUrl, obj).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.autoAddData = function () {
                ybWidget.AutoAddHandoverBill().then(() => {
                    getDataList(1);
                })
            };

            $scope.batchRelease = function () {
                const billNos = $scope.dataList.filter(fItem => fItem.isChecked).map(mItem => mItem.billNo)
                if (billNos.length === 0) {
                    ybWidget.ShowMessage('请选择需要确认下达的行');
                    return;
                }
                ybWidget.ShowMessage("确定要下达吗？", MESG_TYPE.Ask).then(function () {
                    const param = {
                        billNosList: billNos
                    }
                    ybHttp.Post('device', '/deliveryReceipt/batchIssued', param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp.value, MESG_TYPE.Error);
                            return;
                        }
                        if (Array.isArray(resp.value)) {
                            ybWidget.ShowMessage(resp.value.join('<br/>'), MESG_TYPE.Warn, {isHtml: true})
                        } else {
                            ybWidget.ShowToaster('success', '操作成功');
                        }
                        getDataList();
                    });
                }, function () {});
            };

            $scope.deliveryBillNosStr = '';
            $scope.handleMultiInput = function(e) {
                $scope.deliveryBillNosStr = UserContextService.MultiInput(e.target.value);
            };

            $scope.wmsSyncByDeliveryBill = function () {
                $scope.deliveryBillNosStr = '';
                $scope.changeTab(7);
            };

            $scope.handleWmsSyncByDeliveryBill = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = "/wmsSync/manualSyncByDeliveryBillNo";
                ybHttp.Post(service, reqUrl, $scope.deliveryBillNosStr.split(',')).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    const vals = resp.value || [];
                    if (vals.length > 0) {
                        ybWidget.ShowMessage(vals.join('<br/>'), MESG_TYPE.Warn, { isHtml: true });
                    } else {
                        ybWidget.ShowToaster('success', '操作成功');
                    }
                })
            };

            $scope.importWmsSync = function () {
                var param = {
                    name: "WMS数据",
                    templateReqService: "device",
                    templateReqUrl: "/purchaseRequest/downloadJck2WmsExcel",
                    importReqService: "device",
                    importReqUrl: "/purchaseRequest/importJck2WmsExcel",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {});
            };

            function handleAttachFiles(attachNameStr) {
                if (!attachNameStr) {
                    return [];
                }
                return attachNameStr.split(',').map(an => {
                    const fName = an.split('/').pop()
                    return {
                        fileUrl: an,
                        name: fName,
                        filename: fName,
                        hasUpload: true,
                    }
                })
            }

            function viewAttach4sch(item) {
                ybWidget.FileUploader({fileList: handleAttachFiles(item.schAttach), Type: 'view'})
            }

            $scope.importAttach4sch = function(item) {
                ybWidget.FileUploader({fileList: item.attachFiles4sch || handleAttachFiles(item.schAttach), ignoreFormat: true}).then(res => {
                    const fileListTemp  = res.fileList || [];
                    item.attachFiles4sch = fileListTemp;
                    item.schAttach = fileListTemp.filter(item => !!item.fileUrl).map(an => an.fileUrl).join(',');

                    const { id, schAttach } = item;
                    ybHttp.Post('device', '/deliveryReceipt/updateAttach4sch', { id, schAttach }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        }
                    });
                })
            };

            function IsPC() {
                var userAgentInfo = navigator.userAgent.toLowerCase();
                var Agents = ["android", "iphone", "symbianos", "windows phone", "ipad", "ipod"];
                var flag = true;
                for (var v = 0; v < Agents.length; v++) {
                    if (userAgentInfo.indexOf(Agents[v]) > 0) {
                        flag = false;
                        break;
                    }
                }
                return flag;
            };
            $scope.isPC = false;

            // 同步万泰ERPS数据/后加另一承运商恒业
            $scope.syncWTErp = function (id,carrierOrgCode){
                console.log("carrierOrgCode:",carrierOrgCode);
                var service = "device";
                // var reqUrl = "/deliveryReceipt/syncWantaiErp";
                var reqUrl = "";
                var param = {
                    billNo: id
                };
                if (carrierOrgCode == "91320115MA20J0TU4K"){
                    // 承运商为万泰
                    reqUrl = "/deliveryReceipt/syncWantaiErp";
                }else if (carrierOrgCode == "91320300690776470P"){
                    // 承运商为恒业
                    reqUrl = "/deliveryReceipt/syncHengyeErp";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    getDataList();
                });
            };

            // 撤销同步万泰ERPS数据
            $scope.unsyncWTErp = function (id,carrierOrgCode){
                var service = "device";
                // var reqUrl = "/deliveryReceipt/withdrawSyncWantaiErp";
                var reqUrl = "";
                var param = {
                    billNo: id
                };
                if (carrierOrgCode == "91320115MA20J0TU4K"){
                    // 承运商为万泰
                    reqUrl = "/deliveryReceipt/withdrawSyncWantaiErp";
                }else if (carrierOrgCode == "91320300690776470P"){
                    // 承运商为恒业
                    reqUrl = "/deliveryReceipt/withdrawSyncHengyeErp";
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    getDataList();
                });
            };

            (function () {
                $scope.isPC = IsPC();

                if ($state.params.orderNo) {
                    $scope.condition.purchaseNo = $state.params.orderNo
                }
                const waitForSignNum = $state.params.backlogData?.waitForDeliveryReceiptCount; // 待签收的数量
                if (waitForSignNum) {
                    $scope.condition.deliveryStatus = '1';
                    getDataList()
                }

                getDeliveryStatus();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                listWarehouses();
                // 农机新增
                if ($scope.isNJ) {
                    $scope.billTypeList.push({
                        code: "XGZK",
                        name: "赠送出库"
                    },) 
                }
            })();
        }]);
})(window, window.angular);
